<?php

namespace App\Admin\Repositories;

use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Repositories\Repository;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class KaoQinStatisticsApi extends Repository
{

    /**
     * 查询表格数据
     *
     * @param Grid\Model $model
     * @return LengthAwarePaginator
     */
    public function get(Grid\Model $model)
    {
        // 获取筛选参数
        $start = $model->filter()->input('start');
        $end = $model->filter()->input('end');
        $engineering = $model->filter()->input('engineering');
        $engineering_id = DB::table('engineering')->where('engineering_name',$engineering)->value('id');


        $client = new \GuzzleHttp\Client();

        $url = env('APP_URL').'api/kaoQinStatistics';

        $response = $client->get("$url?engineering_id={$engineering_id}&start={$start}&end={$end}");
        $data = json_decode((string)$response->getBody(), true);
        return $data['subjects'];

//        if (isset($_GET['_export_'])) {
//            return $data;
//        }

//        return $model->makePaginator(
//            $data['total'] ?? 0,
//            $data['subjects'] ?? []
//        );
    }

    /**
     * 查询编辑页数据
     *
     * @param Form $form
     * @return array
     */
    public function edit(Form $form): array
    {
        $id = $form->builder()->getResourceId();

        $data = file_get_contents("http://api.douban.com/v2/movie/subject/$id?{$this->apiKey}");

        return json_decode($data, true);
    }

    /**
     * 编辑数据
     *
     * @param Form $form
     */
    public function update(Form $form)
    {
        $id = $form->builder()->getResourceId();

        $attributes = $form->getUpdates();

        // TODO
//        var_dump($id, $attributes);
    }

    /**
     * 查询删除前数据
     *
     * @param Form $form
     * @return array
     */
    public function getDataWhenDeleting(Form $form): array
    {
        $id = $form->builder()->getResourceId();

//        $data = file_get_contents("http://api.douban.com/v2/movie/subject/$id");
//
//        return json_decode($data, true);

        return [];
    }

    /**
     * 删除数据
     *
     * @param Form $form
     * @param array $deletingData
     */
    public function destroy(Form $form, array $deletingData)
    {
        $id = $form->builder()->getResourceId();

        // TODO
//        var_dump($id, $deletingData);
    }

}
